package com.marvels.financial.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.mapper.MapperWrapper;


public class SystemUtil {
	/**
	 * 参数拼装
	 * 
	 * @return
	 */
	public static String paramsAssembling(Map<String, Object> map, String urlStr) {
		StringBuffer urlStringBuffer = new StringBuffer();
		if (StringUtils.isNotEmpty(urlStr)) {
			urlStringBuffer.append(urlStr).append("?");
		}
		int i = 1;
		for (String key : map.keySet()) {
			if (i == map.size()) {
				urlStringBuffer.append(key).append("=").append(map.get(key));
			} else {
				urlStringBuffer.append(key).append("=").append(map.get(key)).append("&");
			}
			i++;
		}
		return urlStringBuffer.toString();

	}
	
	public static String createUUID(String sign) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		String timeStr = simpleDateFormat.format(new Date());
		UUID uuid = UUID.randomUUID();
		String str = uuid.toString();
		// 去掉"-"符号
		String temp = str.replace("-", "").substring(0, 5);
		return timeStr + temp + sign;
	}
	
	
	/**
	 * 将xml解析到实体
	 * 
	 * @param jsonStr
	 * @param clazz
	 * @return
	 */
	public static <T> T xmlToEntity(String xmlStr, Class<T> cls) {
		// 注意：不是new Xstream(); 否则报错：java.lang.NoClassDefFoundError:
		// org/xmlpull/v1/XmlPullParserFactory
		XStream xstream = new XStream() {
			@Override
			protected MapperWrapper wrapMapper(MapperWrapper next) {
				return new MapperWrapper(next) {
					@Override
					public boolean shouldSerializeMember(Class definedIn, String fieldName) {
						if (definedIn == Object.class) {
							try {
								return this.realClass(fieldName) != null;
							} catch (Exception e) {
								return false;
							}
						} else {
							return super.shouldSerializeMember(definedIn, fieldName);
						}
					}
				};
			}
		};
		// xstream.ignoreUnknownElements();
		xstream.processAnnotations(cls);
		T obj = (T) xstream.fromXML(xmlStr);
		return obj;
	}
	
	
	/**
	 * 将xml解析到实体
	 * 
	 * @param jsonStr
	 * @param clazz
	 * @return
	 */
	public static <T> T xmlToEntity2(String xmlStr, Class<T> cls) {
		XStream xstream=new XStream(new DomDriver()); //注意：不是new Xstream(); 否则报错：java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserFactory
		xstream.processAnnotations(cls); //如果是用注解的方式，这句不能少
		T t=(T)xstream.fromXML(xmlStr);
		return t;
	}
}
